import json

from flask import Flask, render_template, jsonify, request
import random
import requests as rst
app = Flask(__name__)

#版本号
version = "1.1"

#页面标题
index_title = "净水装置数据实时监测平台"

#设置网页数据刷新时间，单位：ms
refresh_rate = 3000

# 存储历史数据点的数组
history_data = []

#返回数据demo
esp32_data = {
"temp":[30,40],
"ph":[10, 9],
"ntu": [100, 255],
"ppm":[30,40]
}

#发送的数据。温度，ph，浊度，TDS
bar_data = {
"dirty":[25,2,301.56,420.44],
"clear":[27,9,89.34,200.75]
}

senddata_demo = {
"dirty":[1,14,3,10],
"clear":[9,10,3,1]
}

# 生成随机数据的函数,测试用
def generate_data():
    if len(history_data) > 20:
        history_data.clear()
    new_value = random.randint(0, 7)
    history_data.append(new_value)
    return list(history_data)

def generate_data_bar():
    for index,value in enumerate(senddata_demo["dirty"]) :
        senddata_demo["dirty"][index] = random.randint(0, 14)
    for index,value in enumerate(senddata_demo["clear"]) :
        senddata_demo["clear"][index] = random.randint(0, 14)
    return senddata_demo

#主页
@app.route('/')
def index():
    #渲染模板
    return render_template('index.html',version=version,index_title=index_title,refresh_rate=refresh_rate)


#接收单片机发来的数据
@app.route('/data', methods=['POST'])
def receive_data():
    data = request.get_data()
    esp32_data = json.loads(data)
    print(data)
    #解析单片机发来的数据
    bar_data["dirty"][0] = esp32_data["temp"][0]
    bar_data["clear"][0] = esp32_data["temp"][1]
    bar_data["dirty"][1] = esp32_data["ph"][0]
    bar_data["clear"][1] = esp32_data["ph"][1]
    bar_data["dirty"][2] = esp32_data["ntu"][0]
    bar_data["clear"][2] = esp32_data["ntu"][1]
    bar_data["dirty"][3] = esp32_data["ppm"][0]
    bar_data["clear"][3] = esp32_data["ppm"][1]
    return jsonify({"msg": "success"}), 200
    # try:
    #     data = request.get_data()
    #     data = json.loads(data)
    #     print(data)
    #     return jsonify({"msg": "success"}), 200
    # except:
    #     return jsonify({"msg": "error"}), 400


#图表0的数据，污水缸
@app.route('/get_chart0')
def get_chart0():
    return jsonify(generate_data())


#图表1的数据，净水缸
@app.route('/get_chart1')
def get_chart1():
    return jsonify(generate_data())


#返回柱状图对比数据
@app.route('/get_chartbar')
def get_chartbar():
    # 返回随机数据，测试用
    # return jsonify(generate_data_bar())
    #返回数据
    print(bar_data)
    return jsonify(bar_data)

#没用了，先放一边
# @app.route('/test')
# def index_new():
#     return render_template('index_new.html')
#
# @app.route('/action')
# def action():
#     status = rst.get(url_dirty)
#     # if status = "ok"
#     return render_template('index_new.html')


if __name__ == '__main__':
    app.run("0.0.0.0", "9912",debug=True,threaded=True)